import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:shining_red_star/api/list_number.dart';
import 'package:shining_red_star/model/number.dart';
import 'package:shining_red_star/model/router_params.dart';
import 'package:shining_red_star/utils/play.dart';
import '../../widgets/focus_manage/focus_widget.dart';
import '../../wrappers/safe-area.dart';

class NumberDetailPage extends StatefulWidget {
  const NumberDetailPage({super.key});

  @override
  State<NumberDetailPage> createState() => _NumberDetailPageState();
}

class _NumberDetailPageState extends State<NumberDetailPage> {
  SwiperController controller = SwiperController();
  FocusNode focusNode = FocusNode();
  int currentIndex = 0;
  List<NumberInfo> numberList = [];

  void playAud(int index) async {
    if (numberList.isEmpty) {
      return;
    }
    AudioPlayManager.lowLatencyPlay(numberList[index].aud);
  }

  Future<CommonDetailRouterArguments> getRouterArguments() {
    Completer<CommonDetailRouterArguments> completer = Completer();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      CommonDetailRouterArguments? args = ModalRoute.of(context)
          ?.settings
          .arguments as CommonDetailRouterArguments?;
      completer.complete(args ?? CommonDetailRouterArguments());
    });
    return completer.future;
  }

  void loadData() {
    Future.wait([getRouterArguments(), listNumber()]).then((res) {
      CommonDetailRouterArguments routerArguments =
          res[0] as CommonDetailRouterArguments;
      List<NumberInfo> list = res[1] as List<NumberInfo>;
      if (list.isEmpty) {
        return;
      }
      setState(() {
        numberList = list;
        currentIndex = max(
            list.indexWhere(
                (item) => item.value.toString() == routerArguments.id),
            0);
        playAud(currentIndex);
      });
    });
  }

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeAreaPageWrapper(
      child: numberList.isEmpty
          ? Center(
              child: Text('数据加载中'),
            )
          : FocusWidget(
              focusNode: focusNode,
              autofocus: true,
              onFocusChange: (value) {
                setState(() {});
              },
              onKeyEvent: (node, event) {
                if (event is KeyDownEvent) {
                  switch (event.logicalKey) {
                    case LogicalKeyboardKey.arrowLeft:
                    case LogicalKeyboardKey.arrowRight:
                    case LogicalKeyboardKey.arrowUp:
                    case LogicalKeyboardKey.arrowDown:
                      if (event.logicalKey == LogicalKeyboardKey.arrowLeft ||
                          event.logicalKey == LogicalKeyboardKey.arrowUp) {
                        controller.previous();
                      } else {
                        controller.next();
                      }
                      return KeyEventResult.handled;
                    case LogicalKeyboardKey.enter:
                    case LogicalKeyboardKey.select:
                      playAud(currentIndex);
                      return KeyEventResult.handled;
                  }
                }
                return KeyEventResult.ignored;
              },
              child: Center(
                child: numberList.isNotEmpty
                    ? Swiper(
                        index: currentIndex,
                        itemCount: numberList.length,
                        controller: controller,
                        scrollDirection: Axis.vertical,
                        onTap: (index) {
                          playAud(index);
                        },
                        itemBuilder: (BuildContext context, int index) {
                          return LayoutBuilder(builder: (context, constraints) {
                            double fontSize = min(constraints.maxHeight,
                                    constraints.maxWidth) *
                                0.85;
                            return Center(
                              child: Text(
                                numberList[index].value.toString(),
                                style: TextStyle(fontSize: fontSize, height: 1),
                              ),
                            );
                          });
                        },
                        onIndexChanged: (index) {
                          setState(() {
                            currentIndex = index;
                          });
                          playAud(index);
                        },
                      )
                    : null,
              )),
    );
  }
}
